package com.iiapk.core.widget;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.os.Handler.Callback;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class FlingWebView extends WebView {
	
	protected GestureDetector mGestureDetector;
	protected Context mContext;
	protected String baseUrl;
	
	protected ProgressDialog mPdLoading;
	public static final int DIALOG_BEGIN = 0;
	public static final int DIALOG_END = 1;
	public static final int STATUS_FINISHED = 3;
	protected Handler mHandler = new Handler(new Callback() {
		@Override
		public boolean handleMessage(Message msg) {
			switch (msg.what) {
			case DIALOG_BEGIN:
				mPdLoading.show();
				return true;
			case DIALOG_END:
				mPdLoading.dismiss();
				return true;
			}
			return false;
		}
	});
	
	
	public FlingWebView(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		needToInit();
		setupLoadingDialog();
	}
	
	public FlingWebView(Context context, AttributeSet attrs, String url,Handler handler) {
		this(context,null);
		baseUrl = url;
		mHandler = handler;
		if(baseUrl!=null)
			loadUrl(baseUrl);
	}
	
	private void needToInit(){
		setClickable(true);
		setSelected(false);
		setHorizontalScrollBarEnabled(false);
		setVerticalScrollBarEnabled(true);

		WebSettings webSetting1 = getSettings();
		webSetting1.setJavaScriptEnabled(true);
		webSetting1.setDefaultZoom(WebSettings.ZoomDensity.FAR);
		webSetting1.setDefaultFontSize(24);
		webSetting1.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);

		setWebViewClient(new WebViewClient() {
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				super.onPageStarted(view, url, favicon);
				mHandler.sendEmptyMessage(DIALOG_BEGIN);
			}
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				if(view.getUrl()!=null){
					if(!view.getUrl().equals(url))
						view.loadUrl(url);
				}else{
					view.loadUrl(url);
				}
				return true;
			}
			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				mHandler.sendEmptyMessage(DIALOG_END);
			}
		});
	}
	
	private void setupLoadingDialog() {
		mPdLoading = new ProgressDialog(mContext);
		mPdLoading.requestWindowFeature(Window.FEATURE_NO_TITLE);
		mPdLoading.requestWindowFeature(Window.FEATURE_PROGRESS);
		mPdLoading.requestWindowFeature(Window.FEATURE_OPTIONS_PANEL);
		mPdLoading.setIndeterminate(true);
		mPdLoading.setCancelable(false);
	}
	
}
